package edu.ccut.saturn.web.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.ccut.saturn.component.FilterManager;
import edu.ccut.saturn.component.ISaturnFilter;
import edu.ccut.saturn.component.SaturnResponse;
import edu.ccut.saturn.component.impl.SaturnFilterInfo;

public class RequestFilter implements Filter {

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String contextPath = httpRequest.getContextPath().toString();
		String requestUrl = httpRequest.getRequestURL().toString();
		String requestAction = requestUrl.substring(requestUrl
				.indexOf(contextPath)
				+ contextPath.length());
		requestAction = requestAction.replace("::", "");
		FilterManager filterManager = FilterManager.getInstance();	
		List<SaturnFilterInfo> filterInfos = filterManager.getFilterInfo(requestAction);
		if(filterInfos.size()==0){
			filterChain.doFilter(httpRequest, response);
			return;
		}else{			
			SaturnResponse saturnResponse = null;
			for(SaturnFilterInfo filterInfo:filterInfos){
				ISaturnFilter saturnFilter= filterManager.getSaturnFilter(filterInfo.getClassName());
				saturnResponse = saturnFilter.doFilter(httpRequest);
				if(!saturnResponse.isResponse()){
					httpResponse.sendRedirect(saturnResponse.getUrl());
					return;
				}
			}
			filterChain.doFilter(httpRequest, response);
		}	
	}

	public void init(FilterConfig filterConfig) throws ServletException {

	}

}
